package com.cashmate.struts;

import com.cashmate.hibernate.dao.EmployeeDAO;
import com.cashmate.hibernate.dao.LoanverificationDAO;
import com.cashmate.hibernate.dao.ProductDAO;
import com.cashmate.hibernate.dao.RequestDAO;
import com.cashmate.hibernate.pojo.Employees;
import com.cashmate.hibernate.pojo.Loanverification;
import com.cashmate.hibernate.pojo.Products;
import com.cashmate.hibernate.pojo.Request;
import com.cashmate.hibernate.pojo.Usertypes;
import com.opensymphony.xwork2.ActionSupport;
import java.util.Iterator;
import java.util.Set;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;

public class DeleteRequest extends ActionSupport {

    private static Logger logger = Logger.getLogger(DeleteRequest.class);
    private String oper;
    private String id;
  
    private final RequestDAO requestdao = (RequestDAO) ServletActionContext.getServletContext().getAttribute("requestDAO");
    private final LoanverificationDAO lvdao = (LoanverificationDAO) ServletActionContext.getServletContext().getAttribute("loanverificationDAO");
    
    private Employees emps = (Employees) ServletActionContext.getRequest().getSession().getAttribute("employee");
    private Usertypes ut = (Usertypes) ServletActionContext.getRequest().getSession().getAttribute("usertype");

    @Action(value = "/del-request", results = {
        @Result(name = "duplicate", location = "../error/formError.jsp"),
        @Result(name = "error", location = "../error/messages.jsp")
    })
    @Override
    public String execute() {
        try {
            Request request = null;
            if (oper.equals("del")) {
                request = requestdao.get(Integer.parseInt(id));
                Set<Loanverification> lvset= request.getLoanverificationses();
                Iterator it = lvset.iterator();
                
                while(it.hasNext()){
                    Loanverification element = (Loanverification) it.next();
                    element.setRequest(null);
                    element.setStatus("saved");
                    lvdao.update(element);
                }
                
                requestdao.delete(Integer.parseInt(id));
              
            }
        } catch (Exception e) {
            e.printStackTrace();;
            if (emps != null) {
                logger.fatal("(" + emps.getIdnumber() + "):" + e.getLocalizedMessage(), e);
            } else {
                logger.fatal(e.getLocalizedMessage(), e);
            }
            addActionError(e.getLocalizedMessage());
            return ERROR;
        }
        return NONE;
    }

    public void setId(String id) {
        this.id = id;
    }

    public void setOper(String oper) {
        this.oper = oper;
    }
}
